package cn.yshujia.handler;

import cn.yshujia.encryption.AESEncrypt;
import cn.yshujia.utils.WordReplaceUtils;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author YShuJia
 * @create 2024/12/18
 * @description SensitiveHandler
 */

@Component
public class SensitiveHandler extends BaseTypeHandler<String> {
	
	
	WordReplaceUtils wordReplaceUtils = new WordReplaceUtils();
	
	@Override
	public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
		// 脱敏
		if (s == null) {
			preparedStatement.setString(i, null);
			return;
		}
		String cipherText = SensitiveWordHelper.replace(s, wordReplaceUtils);
		preparedStatement.setString(i, AESEncrypt.encrypt(cipherText));
	}
	
	@Override
	public String getNullableResult(ResultSet resultSet, String s) throws SQLException {
		return AESEncrypt.decrypt(resultSet.getString(s));
	}
	
	@Override
	public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
		return AESEncrypt.decrypt(resultSet.getString(i));
	}
	
	@Override
	public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
		return AESEncrypt.decrypt(callableStatement.getString(i));
	}
}


